import time

import pandas as pd
import json


class BC25:
    ProductKey = "a1TrjKDoflp"
    DeviceName = "testInLinux"
    DeviceSecret = "9bba092d80a47a0ff29c7b1581dc6a28"
    PubTopic = "/sys/a1TrjKDoflp/testInLinux/thing/event/property/post"
    SubTopic = "/sys/a1TrjKDoflp/testInLinux/thing/event/property/post_reply"
    FunctionIdentifier = "bc26UpdataDate"

    def __init__(self, port):
        self.port = port
        print("------------BC25 Init----------------")
        # 连接测试
        self.port.send_data("AT\r\n".encode())
        str_data = self.port.read_data()
        str_data = str_data[-1].decode().rstrip()
        print(str_data + "(OK)")

        # 射频功能是否打开
        self.port.send_data("AT+CFUN?\r\n".encode())
        str_data = self.port.read_data()
        str_data = str_data[1].decode().rstrip()
        print(str_data + "(+CFUN: 1)")

        # 获取卡号
        self.port.send_data("AT+CIMI\r\n".encode())
        str_data = self.port.read_data()
        str_data = str_data[1].decode().rstrip()
        self.card_id = str_data

        # 查询信号质量

        # 查询模块的当前网络状况

        # 激活网络
        self.port.send_data("AT+CGATT?\r\n".encode())
        str_data = self.port.read_data()
        str_data = str_data[1].decode().rstrip()
        self.network_state = str_data.split(': ')[-1]
        print(str_data + "(+CGATT: 1)")  # 应该解析str字符串
        if self.network_state != "1":
            port.send_data("AT+CGATT=1\r\n".encode())
            str_data = port.read_data()
            str_data = str_data[1].decode().rstrip()
            print(str_data + "(+CGATT: 1)")

        # 连接网络
        self.port.send_data("AT+CSCON?\r\n".encode())
        str_data = self.port.read_data()
        str_data = str_data[1].decode().rstrip()
        print(str_data + "(+CSCON: 0,0/1)")

    def mqtt_init(self):
        print("------------MQTT Init----------------")
        # 判断当前是否在线，如果在线就不用初始化了（判断错误了）
        # self.port.send_data('AT+QMTCONN?"\r\n'.encode())
        # str_data = self.port.read_data()
        # if str_data[-1].decode().rstrip() != 'OK':
        #     print('MQTT is connected!')
        #     return

        # 配置阿里云设备信息
        self.port.send_data(('AT+QMTCFG="ALIAUTH",0,"%s","%s","%s"\r\n'
                            % (self.ProductKey, self.DeviceName, self.DeviceSecret)).encode())
        str_data = self.port.read_data()
        str_data = str_data[1].decode().rstrip()
        print('Config aliauth: ' + str_data + '(OK)')

        # 打开MQTT客户端网络
        self.port.send_data('AT+QMTOPEN=0,"iot-as-mqtt.cn-shanghai.aliyuncs.com",1883\r\n'.encode())
        str_data = self.port.read_data()
        # print('Open MQTT network:' + str_data[-1].decode().rstrip() + '(+QMTOPEN: 0,0)')
        print('Open MQTT network:')
        print(str_data)

        # 连接客户端至MQTT服务器
        self.port.send_data(('AT+QMTCONN=0,"%s"\r\n' % self.DeviceName).encode())
        str_data = self.port.read_data()
        # print('Connect to MQTT server: ' + str_data[-1].decode().rstrip() + '(+QMTCONN: 0,0,0)')
        print('Connect to MQTT server: ')
        print(str_data)

    def aliyun_mqtt_pub_data(self, data):
        self.port.send_data(('AT+QMTPUB=0,1,1,0,"%s",' % self.PubTopic).encode())
        # str_json = self.aliyun_mqtt_data2json(data)
        self.port.send_data(('32,\"{\'params\':{\'%s\':%s}}"\r\n'
                             % (self.FunctionIdentifier, str(data))).encode())

        str_data = self.port.read_data()
        print('Send data: ' + str(data) + " " + str_data[-1].decode().rstrip())

    def aliyun_mqtt_data2json(self, data):
        str_tmp = {'params': {self.FunctionIdentifier: data}}
        str_tmp = json.dumps(str_tmp)
        return str(str_tmp).replace(' ', '')

    def colse_mqtt(self):
        self.port.send_data("AT+QMTDISC=0\r\n".encode())
        self.port.send_data("AT+QMTCLOSE=0\r\n".encode())


class BC25LineDetectorData(BC25):
    ProductKey = "a1TrjKDoflp"
    DeviceName = "line_detector_data"
    DeviceSecret = "4f970a5f8de922834cec9adf28fc6a3b"
    PubTopic = "/sys/a1TrjKDoflp/line_detector_data/thing/event/property/post"
    SubTopic = "/sys/a1TrjKDoflp/line_detector_data/thing/event/property/post_reply"
    # FunctionIdentifier = "bc26UpdataDate"
    FunctionIdentifier2 = "PeopleInLine"
    FunctionIdentifier3 = "LineSpeed"
    base_size = 16

    def aliyun_mqtt_pub_data(self, data):
        self.port.send_data(('AT+QMTPUB=0,1,1,0,"%s",' % self.PubTopic).encode())
        # str_json = self.aliyun_mqtt_data2json(data)
        self.port.send_data(('32,\"{\'params\':{\'%s\':%s}}"\r\n'
                             % (self.FunctionIdentifier, str(data))).encode())

        str_data = self.port.read_data()
        print('Send data: ' + str(data) + " " + str_data[-1].decode().rstrip())

    def aliyun_mqtt_pub_data2(self, data):
        self.port.send_data(('AT+QMTPUB=0,1,1,0,"%s",' % self.PubTopic).encode())
        # str_json = self.aliyun_mqtt_data2json(data)

        data_size = self.base_size + len(self.FunctionIdentifier2) + len(str(data))
        self.port.send_data(('%d,\"{\'params\':{\'%s\':%s}}"\r\n'
                             % (data_size, self.FunctionIdentifier2, str(data))).encode())

        str_data = self.port.read_data()
        print('Send data: ' + str(data) + " " + str_data[-1].decode().rstrip())

    def aliyun_mqtt_pub_data3(self, data):
        self.port.send_data(('AT+QMTPUB=0,1,1,0,"%s",' % self.PubTopic).encode())
        # str_json = self.aliyun_mqtt_data2json(data)

        data_size = self.base_size + len(self.FunctionIdentifier3) + len(str(data))
        self.port.send_data(('%d,\"{\'params\':{\'%s\':%s}}"\r\n'
                             % (data_size, self.FunctionIdentifier3, str(data))).encode())

        str_data = self.port.read_data()
        print('Send data: ' + str(data) + " " + str_data[-1].decode().rstrip())


if __name__ == '__main__':
    str_json = {'params': {'aa': 56}}
    str_json = json.dumps(str_json)
    print(len(str_json))
    print(str_json)

